<?php

class TaskController extends Controller {

    /**
     * @todo Test request using httpRequest
     * @link http://www.yiiframework.com/extension/ehttpclient/
     */
    public function actionTest(){
        Yii::import('ext.ehttpclient.*');

        $gatewayURL  =   'http://localhost:9333/ozeki?';
        $request = 'login=admin';
        $request .= '&password=abc123';
        $request .= '&action=sendMessage';
        $request .= '&messageType=SMS:TEXT';
        $request .= '&recepient='.urlencode('+84985050225');
        $request .= '&messageData='.urlencode("Hello World");

        $url =  $gatewayURL . $request;

        $client = new EHttpClient($url, array(
            'maxredirects' => 3,
            'timeout'      => 30,
            'adapter'      => 'EHttpClientAdapterCurl'));

//        $client->setParameterGet(array('hl'=>'es', 'q'=>'xuanhoapro'));

        $response = $client->request();

        if($response->isSuccessful())
            echo $response->getBody();
        else
            $response->getRawBody();
        die();
    }

    public function actionIndex() {
        $this->pageTitle = Yii::t('app', 'Task manager');

        $model = new Task();
        $listContact = ContactPerson::getListContact();

        if(isset($_GET['Task'])) {
            $model->unsetAttributes();
            $model->attributes=$_GET['Task'];
            if($_GET['Task']['id_client']){
                $id_client = (int) $_GET['Task']['id_client'];
                $listContact = ContactPerson::getListContact(true, $id_client);
            }
        }

		//Common::debug($_SESSION);
        $this->render('index', array(
            'model' => $model,
            'listAnalyst'=>Admin::getListAnalyster(),
            'listAttributeMatter' => Attribute::getListAttribute(),
            'listContact' => $listContact,
        ));
    }

    public function actionView($id = null) {
        $this->pageTitle = Yii::t('app', 'Task manager');
        if (!$id) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Missing parameters!'));
            $this->redirect(array('task/index'));
        }

        $model = Task::model()->findByPk($id, 'del_flg = 0');
        if (!$model) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Invalid record!'));
            $this->redirect(array('task/index'));
        }

        //update status for task
        if (isset($_POST['Task']) && $data = $_POST['Task']) {
            $model->attributes = $data;
            if ($model->save()) {
                if($data['status']==Constant::STATUS_CLOSE){
                    // send sms to transporter


                    // sendemail to contact person
                }

                Yii::app()->user->setFlash('success', Yii::t('app', 'Status updated success!'));
                $this->redirect(array('task/index'));
            }else{
                Yii::app()->user->setFlash('error', Yii::t('app', 'Task update false!'));
            }
        }

        // get all data view Task
        $data = array();
        $data['client_company'] = $model->client->company_name;
        $data['contact'] = $model->cp->first_name. ' '. $model->cp->last_name;
//        $data['trensporter_company'] = $model->transport->company_name;
        $data['trensporter'] = $model->td->name;
        $data['attribute_matter'] = $model->attribute_matter->name;
        $data['content_matter'] = $model->attribute_matter->note;
        $data['deadline'] = $model->deadline;
        $data['delivery_date'] = $model->delivery_date;
        $data['status'] = Constant::getStatus($model->status);

        // get all data special analyst for task when view task
        $modelTaskAnalyst = new TaskAnalyst();
        $dataTaskAnalyst = $modelTaskAnalyst->search_task($model->id_task, true);
        if(sizeof($dataTaskAnalyst)){
            foreach($dataTaskAnalyst as $taskAnalyst){
                if($taskAnalyst->special_analyst){
                    $criteriaSpecial = new CDbCriteria();
                    $criteriaSpecial->addCondition('id_task_analyst = :id_task_analyst');
                    $criteriaSpecial->params = array(':id_task_analyst' => $taskAnalyst->id_task_analyst);
                    $modelTaskAnalystSpecial = TaskAnalystSpecial::model()->find($criteriaSpecial);

                    // process post data special analyst for task
                    if (isset($_POST['TaskAnalystSpecial']) && $dataSpecial = $_POST['TaskAnalystSpecial']) {
                        $modelTaskAnalystSpecial->attributes = $dataSpecial;
                        if ($modelTaskAnalystSpecial->save()) {
                            Yii::app()->user->setFlash('success', Yii::t('app', 'Analyst special updated success!'));
                        }else{
                            Yii::app()->user->setFlash('error', Yii::t('app', 'Analyst special update false!'));
                        }
                    }

                    break;
                }
            }
        }

//        Common::debugdie($modelTaskAnalystSpecial);
        $this->render('view', array(
            'model' => $model,
            'data' => $data,
            'modelTaskAnalyst' => $modelTaskAnalyst,
            'modelTaskAnalystSpecial' => (isset($modelTaskAnalystSpecial) ? $modelTaskAnalystSpecial : null),
        ));
    }

    public function actionAnalyststt(){
        if (isset($_POST['status']) && isset($_POST['ids']) && $_POST['status'] && $_POST['ids']) {
            $stt = $_POST['status'];
            $arrIds = $_POST['ids'];
            $idAnalyster = $_POST['id_analyster'];
            $transaction = Yii::app()->db->beginTransaction();
            try {
                $errors = array();
                $errorMessages = '';
                $mailStatus = array();

                $i=0;
                foreach($arrIds as $id){
                    $modelTaskAnalyst = TaskAnalyst::model()->findByPk($id, 'del_flg = 0');
                    $modelTaskAnalyst->status = $stt;
                    if (!$modelTaskAnalyst->save()) {
                        $errors[] = $modelTaskAnalyst->getErrors();
                    }else{
                        $mailStatus[$i]['stt'] = $stt;
                        $mailStatus[$i]['step'] = $modelTaskAnalyst->step_analyst;
                        $i++;
                    }
                }

                //Process error message
                if ($errors) {
                    foreach ($errors as $k => $v) {
                        foreach ($v as $f) {
                            foreach ($f as $id => $m) {
                                $errorMessages .= $m.'<br>';
                            }
                        }
                    }
                }

                if (!empty($errorMessages)) throw new Exception();
                $transaction->commit();

                $analysterModel = Admin::getAnalysterDetail($idAnalyster);
                if(!empty($mailStatus) && $analysterModel){

                    //send mail confirm status from admin to analyster
                    $sub = Yii::t('app', 'Confirm status step analyst');
                    $content = Yii::t('app', 'Hi ').$analysterModel->firstname.' '.$analysterModel->lastname.'!<br>';
                    $content .= Yii::t('app', 'Step analyst status: ').'<br>';
                    foreach($mailStatus as $value){
                        $content .= '<i>'.$value['step']. ' : </i><b>'. Constant::getStatus($value['stt']).'</b><br>';
                    }
                    Common::sentMail($analysterModel->email, $sub, $content);
                }

                Yii::app()->user->setFlash('success', Yii::t('app', 'Update status process analyst in task successful!'));
                $this->redirect(array('task/view', 'id'=>$_POST['id_task']));

            } catch (Exception $e) {
                $transaction->rollback();
                Yii::app()->user->setFlash('error', "$errorMessages");
            }

        }else{
            Yii::app()->user->setFlash('error', Yii::t('app', 'Please check step process analyst or choose status!'));
            $this->redirect(array('task/view', 'id'=>$_POST['id_task']));
        }
    }

    public function actionAdd(){
        $this->pageTitle = Yii::t('app', 'Task manager');

        $model = new Task();

        if (isset($_POST['Task']) && $data = $_POST['Task']) {
            $transaction = Yii::app()->db->beginTransaction();
            try {
                $errors = array();
                $errorMessages = '';

                $model->attributes = $data;
                $model->status = Constant::STATUS_PENDING;

                if (!$model->save()) {
                    $errors[] = $model->getErrors();
                }else{
                    //process task detail (steps process analyst)
                    $matterAttribute = Attribute::getAttributeById($model->id_attribute);
                    $listStepsAnalyst = explode(',', $matterAttribute->id_analysis);

                    // process save steps analysis to task
                    if($listStepsAnalyst){
                        // add first analyst:
                        $modelTaskAnalyst = new TaskAnalyst();
                        $modelTaskAnalyst->id_task = $model->id_task;
                        $modelTaskAnalyst->status = Constant::STATUS_COMPLATE;
                        $modelTaskAnalyst->step_analyst = 'entrée';
                        if (!$modelTaskAnalyst->save()) {
                            $errors[] = $modelTaskAnalyst->getErrors();
                        }

                        //add all process analysis
                        foreach($listStepsAnalyst as $value){
                            //model analyst
                            $criteriaAna=new CDbCriteria;
                            $criteriaAna->addCondition('del_flg = 0');
                            $analysisObj = Analysis::model()->findByPk($value, $criteriaAna);
                            if($analysisObj){
                                $modelTaskAnalyst = new TaskAnalyst();
                                $modelTaskAnalyst->id_task = $model->id_task;
                                if($analysisObj->special_step){
                                    $modelTaskAnalyst->special_analyst = $analysisObj->special_step;
                                }

                                if($analysisObj->default_complate){
                                    $modelTaskAnalyst->status = Constant::STATUS_COMPLATE;
                                }else{
                                    $modelTaskAnalyst->status = Constant::STATUS_PENDING;
                                }
                                $modelTaskAnalyst->step_analyst = $analysisObj->steps;

                                if (!$modelTaskAnalyst->save()) {
                                    $errors[] = $modelTaskAnalyst->getErrors();
                                }

                                if(isset($modelTaskAnalyst->id_task_analyst) && $modelTaskAnalyst->special_analyst){
                                    //add record special analyst
                                    $modelAnalystSpecial = new TaskAnalystSpecial();
                                    $modelAnalystSpecial->id_task_analyst = $modelTaskAnalyst->id_task_analyst;
                                    if (!$modelAnalystSpecial->save()) {
                                        $errors[] = $modelAnalystSpecial->getErrors();
                                    }
                                }


                            }
                        }

                        // add last analyst:
                        $modelTaskAnalyst = new TaskAnalyst();
                        $modelTaskAnalyst->id_task = $model->id_task;
                        $modelTaskAnalyst->status = Constant::STATUS_PENDING;
                        $modelTaskAnalyst->step_analyst = 'sortie';
                        if (!$modelTaskAnalyst->save()) {
                            $errors[] = $modelTaskAnalyst->getErrors();
                        }

                    }else{
                        $errorMessages .= Yii::t('app', 'Missing parameters analyst in matter!').'<br>';
                    }
                }
//                Common::debug($errorMessages);
//                Common::debugdie($errors);

                //Process error message
                if ($errors) {
                    foreach ($errors as $k => $v) {
                        foreach ($v as $f) {
                            foreach ($f as $id => $m) {
                                $errorMessages .= $m.'<br>';
                            }
                        }
                    }
                }

                if (!empty($errorMessages)) throw new Exception();
                $transaction->commit();

                //sent mail to client

                if($model->mail_sent_contact){
                    $contactDetail = ContactPerson::getObjContactDetail($model->id_contact);
                    $contentClient = Yii::t('app', 'Client reference number').': '.$model->client_reference.'<br>';
                    $contentClient .= nl2br($model->conten_mail_client);
                    $subject = ($model->client_reference ? $model->client_reference : $model->id_by_matter);
                    Common::sentMail($contactDetail->email, $subject, $contentClient);
                    Yii::log(array(
                        'email'=>$contactDetail->email,
                        'subject'=>$subject,
                        'contentClient'=>$contentClient,
                    ), CLogger::LEVEL_INFO, 'mail_to_contact');
                }
                // commnent : user get to server LDAP not using email
                /*
                //sent mail to responsible
                $analystDetail = Admin::getAnalysterDetail($model->responsible);
                $content = Yii::t('app', 'Hi ').$analystDetail->firstname.' '.$analystDetail->lastname. '!<br>';
                $content .= Yii::t('app', 'New task detail').'<br>';

                Common::sentMail($analystDetail->email, Yii::t('app', 'New Task'), $content);
                */

                Yii::app()->user->setFlash('success', Yii::t('app', 'Task created success!'));
                $this->redirect(array('task/index'));

            } catch (Exception $e) {
                $transaction->rollback();
                Yii::app()->user->setFlash('error', "$errorMessages");
            }
        }

        $this->render('add', array(
            'model' => $model,
            'listClient' => Client::getListClient(),
            'listComTran' => Transporter::getListTransporter(),
            'listAttributeMatter' => Attribute::getListAttribute(),
            'listAnalyst'=>Admin::getListAnalyster(),
            'listTrensporter' => TransporterDetail::getListTransporter($model->id_transporter),
        ));
    }

    public function actionUpdate($id = null) {
        $this->pageTitle = Yii::t('app', 'Task manager');
        if (!$id) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Missing parameters!'));
            $this->redirect(array('task/index'));
        }

        $model = Task::model()->findByPk($id, 'del_flg = 0');
        if (!$model) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Invalid record!'));
            $this->redirect(array('task/index'));
        }

        if (isset($_POST['Task']) && $data = $_POST['Task']) {
            $model->attributes = $data;
            if ($model->save()) {
                Yii::app()->user->setFlash('success', Yii::t('app', 'Task updated success!'));
                $this->redirect(array('task/index'));
            }else{
                Yii::app()->user->setFlash('error', Yii::t('app', 'Task update false!'));
            }
        }

        $this->render('update', array(
            'model' => $model,
            'listClient' => Client::getListClient(),
            'listContact' => ContactPerson::getListContact(true, $model->id_client),
            'listTrensporter' => TransporterDetail::getListTransporter($model->id_transporter),
            'listComTran' => Transporter::getListTransporter(),
            'listAttributeMatter' => Attribute::getListAttribute(),
            'listAnalyst'=>Admin::getListAnalyster(),

        ));
    }

    public function actionDelete($id = null) {
        if (!$id) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Missing parameters!'));
            $this->redirect(array('task/index'));
        }

        $model = Task::model()->findByPk($id, 'del_flg = 0');
        if (!$model) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Invalid record!'));
            $this->redirect(array('task/index'));
        }

        $model->del_flg = 1;
        if ($model->save(false)) {
            if(!isset($_GET['ajax'])){
                Yii::app()->user->setFlash('success', Yii::t('app', 'Task - Deleted Successfully'));
                $this->redirect(array('task/index'));
            }
            else{
                echo '<div class="alert alert-success fade in"><button type="button" class="close" data-dismiss="alert">×</button>'.Yii::t('app', 'Task - Deleted Successfully').'</div>';
                die();
            }

        }

    }

    public function actionFilterClient(){
        if(isset($_POST['Task']['id_client'])&& $idClient = $_POST['Task']['id_client']){
            $listContact = ContactPerson::_getContactByClient($idClient);
//            Common::debugdie($listContact);
            $_htmlOptionSelect = '<option value="">'.Yii::t('app', 'Please select contact').'</option>';
            if($listContact){
                foreach($listContact as $value){
                    $_htmlOptionSelect .= '<option value="'.$value->id_contact.'">'.$value->first_name.' '.$value->last_name.'</option>';
                }
            }
            die($_htmlOptionSelect);
        }
    }

    public function actionFilterTransporter(){
        if(isset($_POST['Task']['id_transporter'])&& $id = $_POST['Task']['id_transporter']){
            $listTransporterDetail = TransporterDetail::_getTransporterByCompany($id);
            $_htmlOptionSelect = '<option value="">'.Yii::t('app', 'Please select transporter').'</option>';
            if($listTransporterDetail){
                foreach($listTransporterDetail as $value){
                    $_htmlOptionSelect .= '<option value="'.$value->id_tpdetail.'">'.$value->name.'</option>';
                }
            }
            die($_htmlOptionSelect);
        }
    }

    public function actionGeneratecode(){
        $result = array();
        $_value = '';
        if(isset($_POST['Task']['id_attribute'])&& $id = $_POST['Task']['id_attribute']){
            $criteria=new CDbCriteria;
            $criteria->addCondition('del_flg = 0');
            $attributeDetail = Attribute::getAttributeById($id);
            if($attributeDetail){
                $_value .= date('y').'-'.$attributeDetail->mt->code.'-'.$attributeDetail->id_attribute;
            }
        }
        $result['code']=$_value;
        $result['print']=$this->createUrl('task/print', array('c'=>$_value));
        die(json_encode($result));
    }

    public function actionPrint(){
        if (!isset($_GET['c']) || !$_GET['c']) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Missing parameters!'));
            $this->redirect(array('task/index'));
        }

        $this->pageTitle = Yii::t('app', 'Print generate code matter');
        $this->layout = '//layouts/print';
        $code = $_GET['c'];
        $this->render('print', array('code'=>$code));
    }

}